<?php

namespace addons\epay\controller;

use addons\epay\library\Service;
use addons\epay\library\Wechat;
use addons\third\model\Third;
use app\common\library\Auth;
use think\addons\Controller;
use think\Response;
use think\Session;
use Yansongda\Pay\Exceptions\GatewayException;
use Yansongda\Pay\Pay;
use app\common\model\OrderPay;
use app\admin\model\Play as PlayModel;
use app\common\model\Order;
use app\common\model\OrderLog;
use think\Db;
use app\api\service\UserService;
use app\common\model\User;

/**
 * API接口控制器
 *
 * @package addons\epay\controller
 */
class Api extends Controller
{

    protected $layout = 'default';
    protected $config = [];

    /**
     * 默认方法
     */
    public function index()
    {
        return;
    }

    /**
     * 外部提交
     */
    public function submit()
    {
        $this->request->filter('trim');
        $out_trade_no = $this->request->request("out_trade_no");
        $title = $this->request->request("title");
        $amount = $this->request->request('amount');
        $type = $this->request->request('type');
        $method = $this->request->request('method', 'web');
        $openid = $this->request->request('openid', '');
        $auth_code = $this->request->request('auth_code', '');
        $notifyurl = $this->request->request('notifyurl', '');
        $returnurl = $this->request->request('returnurl', '');

        if (!$amount || $amount < 0) {
            $this->error("支付金额必须大于0");
        }

        if (!$type || !in_array($type, ['alipay', 'wechat'])) {
            $this->error("支付类型错误");
        }

        $params = [
            'type'         => $type,
            'out_trade_no' => $out_trade_no,
            'title'        => $title,
            'amount'       => $amount,
            'method'       => $method,
            'openid'       => $openid,
            'auth_code'    => $auth_code,
            'notifyurl'    => $notifyurl,
            'returnurl'    => $returnurl,
        ];
        return Service::submitOrder($params);
    }

    /**
     * 微信支付(公众号支付&PC扫码支付)
     * @return string
     */
    public function wechat()
    {
        $config = Service::getConfig('wechat');

        $isWechat = stripos($this->request->server('HTTP_USER_AGENT'), 'MicroMessenger') !== false;
        $isMobile = $this->request->isMobile();
        $this->view->assign("isWechat", $isWechat);
        $this->view->assign("isMobile", $isMobile);

        //发起PC支付(Scan支付)(PC扫码模式)
        if ($this->request->isAjax()) {
            $pay = Pay::wechat($config);
            $orderid = $this->request->post("orderid");
            try {
                $result = $pay->find($orderid, 'scan');
                if ($result['return_code'] == 'SUCCESS' && $result['result_code'] == 'SUCCESS') {
                    $this->success("", "", ['status' => $result['trade_state']]);
                } else {
                    $this->error("查询失败");
                }
            } catch (GatewayException $e) {
                $this->error("查询失败");
            }
        }

        $orderData = Session::get("wechatorderdata");
        if (!$orderData) {
            $this->error("请求参数错误");
        }
        if ($isWechat && $isMobile) {
            //发起公众号(jsapi支付),openid必须

            //如果没有openid，则自动去获取openid
            if (!isset($orderData['openid']) || !$orderData['openid']) {
                $orderData['openid'] = Service::getOpenid();
            }

            $orderData['method'] = 'mp';
            $type = 'jsapi';
            $payData = Service::submitOrder($orderData);
            if (!isset($payData['paySign'])) {
                $this->error("创建订单失败，请返回重试", "");
            }
        } else {
            $orderData['method'] = 'scan';
            $type = 'pc';
            $payData = Service::submitOrder($orderData);
            if (!isset($payData['code_url'])) {
                $this->error("创建订单失败，请返回重试", "");
            }
        }
        $this->view->assign("orderData", $orderData);
        $this->view->assign("payData", $payData);
        $this->view->assign("type", $type);

        $this->view->assign("title", "微信支付");
        return $this->view->fetch();
    }

    /**
     * 支付宝支付(PC扫码支付)
     * @return string
     */
    public function alipay()
    {
        $config = Service::getConfig('alipay');

        $isWechat = stripos($this->request->server('HTTP_USER_AGENT'), 'MicroMessenger') !== false;
        $isMobile = $this->request->isMobile();
        $this->view->assign("isWechat", $isWechat);
        $this->view->assign("isMobile", $isMobile);

        if ($this->request->isAjax()) {
            $orderid = $this->request->post("orderid");
            $pay = Pay::alipay($config);
            try {
                $result = $pay->find($orderid, 'scan');
                if ($result['code'] == '10000' && $result['trade_status'] == 'TRADE_SUCCESS') {
                    $this->success("", "", ['status' => $result['trade_status']]);
                } else {
                    $this->error("查询失败");
                }
            } catch (GatewayException $e) {
                $this->error("查询失败");
            }
        }

        //发起PC支付(Scan支付)(PC扫码模式)
        $orderData = Session::get("alipayorderdata");
        if (!$orderData) {
            $this->error("请求参数错误");
        }

        $orderData['method'] = 'scan';
        $payData = Service::submitOrder($orderData);
        if (!isset($payData['qr_code'])) {
            $this->error("创建订单失败，请返回重试");
        }

        $type = 'pc';
        $this->view->assign("orderData", $orderData);
        $this->view->assign("payData", $payData);
        $this->view->assign("type", $type);
        $this->view->assign("title", "支付宝支付");
        return $this->view->fetch();
    }

    /**
     * 支付成功回调
     */
    public function notifyx()
    {
        // $json = '{"appid":"wx25ea4b51ef23adac","bank_type":"OTHERS","cash_fee":"10","fee_type":"CNY","is_subscribe":"N","mch_id":"1644161646","nonce_str":"EQCFnmociqWiUKjo","openid":"o-g1H6R56_Fg3dbNKCDzgkrzH5DA","out_trade_no":"808921375299","result_code":"SUCCESS","return_code":"SUCCESS","sign":"FF737E4D1C7794AF21D1CAF1AE38FA0C","time_end":"20240903220643","total_fee":"10","trade_type":"JSAPI","transaction_id":"4200002358202409031168935033"}';
        // $param = json_decode($json,1);
        // var_dump('http://chbc.taozhenhao.com/addons/epay/api/notifyx/type/alipay?'.http_build_query($param));exit;
        $type = $this->request->param('type');
        $pay = \addons\epay\library\Service::checkNotify($type);
        \think\Log::write('验签结果:'.json_encode($pay));
        if (!$pay) {
            echo '签名错误';
            \think\Log::write('签名错误');
            return;
        }
        $data = $pay->verify();

        //你可以在这里你的业务处理逻辑,比如处理你的订单状态、给会员加余额等等功能
        $param = $this->request->param();
        if ($type=='wechat') {
            $param = $data;
        }
        $OrderPay = OrderPay::where('pay_no',$param['out_trade_no'])->find();
        if ($OrderPay['pay_status']==1) {
            \think\Log::write('orderpay:已支付');
            echo '已支付';
            return;
        }
        if (!$OrderPay || !$OrderPay['play_nos']) {
            \think\Log::write('paydata:无支付单号');
            echo '参数有误';
            return;
        }
        $User = new \app\common\model\User();
        $userinfo = $User->get($OrderPay['user_id']);
        $order_nos = [];
        $play_nos = [];
        Db::startTrans();
        // try {
            // foreach ($play as $k1 => $v1) {
            $order = Db::name('order_pay_item')->alias('opi')->join('play_order po','po.play_order_no=opi.play_order_no')->field('po.*')->where(['opi.pay_no'=>$OrderPay['pay_no']])->select();
            // 每个店铺的支付总金额
            $sum = [];
            if ($order) {
                foreach ($order as $key => $value) {
                    $is_finish=0;
                    if (!in_array($value['play_no'], $play_nos)) {
                        $play_nos[] = $value['play_no'];
                    }
                    // 如果是大额返利，此时执行完成订单
                    $play = PlayModel::where('play_no', $value['play_no'])->find();
                    if ($value['order_status']==6 || ($value['order_status']==-9 && $value['is_fushen']==1)) {
                        // 分销和抽奖机会和积分
                        // OrderLog::create([
                        //     'play_order_id' => $value['id'],
                        //     'play_order_no' => $value['play_order_no'],
                        //     'info' => '订单完成',
                        //     'create_by' => $user['nickname'],
                        //     'create_by_id' => $user['id'],
                        //     'is_front' => 1,
                        // ]);
                        Order::where(['id'=>$value['id']])->update(['order_status'=>3,'is_pay'=>1,'pay_time'=>time()]);
                        $is_finish=2;
                    } else {
                        Order::where(['id'=>$value['id']])->update(['is_pay'=>1,'pay_time'=>time()]);
                        $is_finish=0;
                    }
                    
                    // orderlog
                    OrderLog::create([
                        'play_order_id' => $value['id'],
                        'play_order_no' => $value['play_order_no'],
                        'create_by' => $userinfo['nickname'],
                        'create_by_id' => $userinfo['id'],
                        'is_front' => 1,
                        'info' => '商家支付h5账单',
                        'is_finish' =>$is_finish,
                    ]);
                    $order_nos[] = $value['play_order_no'];
                    // 中间人佣金
                    $shop = Db::name('shop')->where(['shop_no'=>$value['shop_no']])->field('middleman_id,shop_no')->find();
                    // $middleman = Db::name('middleman')->where(['id'=>$shop['middleman_id']])->field('rebate_amt,user_id')->find();
                    // if (isset($middleman['rebate_amt']) && $middleman['rebate_amt']) {
                    //     $User->money($middleman['rebate_amt'], $middleman['user_id'], '经纪人收益', $value['play_order_no']);
                    // }
                    $amt = round($value['service_charge_amt']+$value['actual_rebate_amt'],2);
                    if (!isset($sum[$shop['shop_no']])) {
                        $sum[$shop['shop_no']] = $amt;
                    } else {
                        $sum[$shop['shop_no']] = $sum[$shop['shop_no']]+$amt;
                    }
                }
            }
            $OrderPay->pay_status = 1;
            $tran_no = '';
            if ($type=='alipay') {
                $tran_no = $param['trade_no'];
            } elseif ($type=='wechat') {
                $tran_no = $param['transaction_id'];
            }
            $OrderPay->tran_no = $tran_no;
            $OrderPay->save();

            // 更新商家账单
            $bill_list = Db::name('bill_list')->order('id DESC')->find();
            if ($sum) {
                foreach ($sum as $key => $value) {
                    $where = 'create_dt="'.$bill_list['create_dt'].'" and shop_no='.$key;
                    $bill_list = Db::name('bill_list')->where($where)->field('*')->find();
                    if ($bill_list) {
                        \think\Log::write('orderpay:'.$where);
                        $update = [];
                        $play_status = '正常';
                        $last_pay_time = time();// 到账时间
                        $play = Db::name('play')->where('play_status in (3,5) and shop_no='.$key.' and pay_status!=2')->where('update_dt<"'.date('Y-m-d H:i:s',time()-259200).'"')->count();
                        if ($play) {
                            $play_status = '紧急账单';
                        }
                        $play = Db::name('play')->where('play_status in (3,5) and shop_no='.$key.' and pay_status!=2')->where('update_dt<"'.date('Y-m-d H:i:s',time()-777600).'"')->count();
                        if ($play) {
                            $play_status = '异常账单';
                        }
                        $amount = $bill_list['total_money']-$value;
                        $update['last_pay_time'] = 0;
                        $update['total_money'] = 0;
                        $update['pay_status'] = '';
                        $update['nopay_dt'] = '1970-01-01 00:00:00';
                        if ($amount>0) {
                            $update['pay_status'] = '待支付';
                            $update['total_money'] = round($amount,2);
                            $corder = Db::name('play_order')->field('create_dt')->where(['shop_no'=>$key])->where('is_pay=0 and order_status in (3,6,-9) and create_dt<"'.substr($bill_list['create_dt'], 0,10).'"')->order('create_dt asc')->find();
                            if ($corder) {
                                $update['nopay_dt'] = $corder['create_dt'];
                            }
                        } else {
                            $update['pay_status'] = '已支付';
                            $update['last_pay_time'] = $last_pay_time;
                        }
                        $update['play_status'] = $play_status;
                        $update['update_dt'] = date('Y-m-d H:i:s',time());
                        Db::name('bill_list')->where('id='.$bill_list['id'])->update($update);
                    }
                }
            }
            Db::commit();
            foreach ($order as $o) {
                if ($o['order_status']==6) {
                    \fast\Http::get(config('chbc_domain').'/index/yunzhan/notify?order_sn='.$o['play_order_no'].'&state=3&source=2&origin=bdb');
                }
            }
        // } catch (Exception $e) {
        //     Db::rollback();
        //     \think\Log::write('paydata:'.print_r($e->getMessage()));
        //     echo '处理有误';
        //     return;
        // }
        //下面这句必须要执行,且在此之前不能有任何输出
        return $pay->success()->send();
    }

    /**
     * 支付成功返回
     */
    public function returnx()
    {
        // $param = [
        //     'charset' => 'utf-8',
        //   'out_trade_no' => 'test34576566666',
        //   'method' => 'alipay.trade.wap.pay.return',
        //   'total_amount' => '0.10',
        //   'sign' => 'SNMA/lJT6/ZRxoggqnBqsPA8T8bXLMmax1CRLYid7yLiSCeaXNDqMp84SXCJlN47kO+vobjMnc0mYM6ix9mndGyTE47Fw/ROEKVfSVFoKPK91PPsv1Spec8kYNSdcrEeBVQXCocxbB6wgZunCIc46JWDnjZzKHzoC/QJr65OVHrRQdXE4f8T4JUX5j1UbOqHIzW/ukyRPbDu1+sCtXU+irHE2lLZ8VfkxyVJqCqDBClEdpBZbwRYQkNM4iKNCER4m6/W3XQz9LONL0TlURZXnIFLNnvIM+J2O9kuEX2Eie3TbAba64xeNY9dzIbfST0rcwGTet99/1ybpUQPlst66Q==',
        //   'trade_no' => '2023042522001498711459239646',
        //   'auth_app_id' => '2021003186663016',
        //   'version' => '1.0',
        //   'app_id' => '2021003186663016',
        //   'sign_type' => 'RSA2',
        //   'seller_id' => '2088641013979026',
        //   'timestamp' => '2023-04-25 11:01:36',
        //   'addon' => 'epay',
        //   'controller' => 'api',
        //   'action' => 'returnx',
        //   'type' => 'alipay',
        // ];
        $type = $this->request->param('type');
        if (!Service::checkReturn($type)) {
            echo '签名错误';
            return;
        }

        //你可以在这里定义你的提示信息,但切记不可在此编写逻辑
        $this->success("恭喜你！支付成功!", config('h5_domain'));

        return;
    }

}
